package com.tianji.promotion.Task;

import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.enums.CouponStatus;
import com.tianji.promotion.service.ICouponService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class TaskForIssueCoupon {
    private final ICouponService couponService;

    @XxlJob("IssueCoupon")
    public void issueCoupon() {
        log.info("发放优惠券任务开始");
        //1.先获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //2.去数据库中查询处于未开始且发放时间早于当前时间的优惠券
        List<Coupon> coupons = couponService.lambdaQuery()
                .eq(Coupon::getStatus, CouponStatus.UN_ISSUE)
                .le(Coupon::getIssueBeginTime, now)
                .list();
        if(coupons == null || coupons.isEmpty()) {
            return ;
        }
        //3.遍历优惠券
        for (Coupon coupon : coupons) {
            //3.1设置优惠券状态为已发放
            coupon.setStatus(CouponStatus.ISSUING.getValue());
        }
        //3.2更新优惠券
        couponService.updateBatchById(coupons);
    }

    @XxlJob("StopIssueCoupon")
    public void stopIssueCoupon() {
        log.info("停止发放优惠券任务开始");
        //1.查询当前时间
        LocalDateTime now = LocalDateTime.now();
        //2.查询当前时间正在发放的优惠券
        List<Coupon> coupons = couponService.lambdaQuery()
                .eq(Coupon::getStatus, CouponStatus.ISSUING)
                .le(Coupon::getIssueEndTime, now)
                .list();
        if(coupons == null || coupons.isEmpty()) {
            return ;
        }
        //3.遍历优惠券
        for (Coupon coupon : coupons) {
            //3.1设置优惠券状态为已发放
            coupon.setStatus(CouponStatus.FINISHED.getValue());
        }
        //3.2更新优惠券
        couponService.updateBatchById(coupons);
    }
}
